package com.wn.trade.service.impl;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wn.common.model.bank.dto.BaseResult;
import com.wn.common.model.borrow.BorrowRecordDTO;
import com.wn.common.model.borrow.BorrowRecordQuery;
import com.wn.common.model.borrow.BorrowRecordVo;
import com.wn.common.model.borrow.BorrowSyncRecordVo;
import com.wn.common.model.user.vo.UserInfoVo;
import com.wn.common.result.Result;
import com.wn.common.utils.Pages;
import com.wn.common.utils.TokenUtils;
import com.wn.sddfp.client.bank.TradeLogApi;
import com.wn.sddfp.client.user.UserApi;
import com.wn.trade.entity.BorrowRecord;
import com.wn.trade.mapper.BorrowRecordMapper;
import com.wn.trade.service.IBorrowRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @author yellow Docter
 * @date 2023 -07-31
 * @desc    Primary可以理解为默认优先选择, 同时不可以同时设置多个,
 *          内部实质是设置BeanDefinition的primary属性
 */
@Slf4j
@Service
public class IBorrowRecordServiceImpl extends ServiceImpl<BorrowRecordMapper, BorrowRecord> implements IBorrowRecordService {

    @Autowired
    private UserApi userApi;

    @Autowired
    private TradeLogApi tradeLogApi;

    @Override
    public void borrow(BorrowRecordDTO borrowRecordDTO) {
        // 1、拿到用户信息
        //  01 请求中有一个 userId
        Long userId = TokenUtils.getTokenUserId();

        //  02 远程调用 拿到userinfo 信息  远程调用 system-service 拿到user信息
        Result<UserInfoVo> result = userApi.findById(userId);
        UserInfoVo userInfoVo = result.getData();

        // 2、创建一个 借款记录 存储
        BorrowRecord borrowRecord = new BorrowRecord();

        //设置数据
        borrowRecord.setUserId(userId);
        borrowRecord.setUserCode(userInfoVo.getUserCode());
        //借款记录
        String recordNo = UUID.randomUUID().toString().substring(0, 10);
        borrowRecord.setBorrowRecordNo("BO_" + recordNo);
        borrowRecord.setDescription("贷款上班");
        borrowRecord.setType("生活贷");

        //借款天数
        borrowRecord.setPeriod(borrowRecordDTO.getPeriod());
        //投资年化利率
        borrowRecord.setInvestRate(new BigDecimal("0.03"));
        //借款年化利率
        borrowRecord.setBorrowerRate(new BigDecimal("0.03"));
        //COMMISSION_RATE
        borrowRecord.setCommissionRate(new BigDecimal("0.03"));

        //等额本息 (和后期的还款有关系)
        borrowRecord.setRepaymentWay("DEBX");

        // 借款金额
        borrowRecord.setAmount(borrowRecordDTO.getAmount());
        borrowRecord.setBorrowStatus("新建");

        //创建时间
        borrowRecord.setCreateDate(new Date());
        //确认时间
        borrowRecord.setModifyDate(new Date());
        //是否同步
        borrowRecord.setStatus(false);
        //请求流水
        String reqCode = UUID.randomUUID().toString().substring(0, 10);
        borrowRecord.setReqCode("BORROW_" +reqCode);

        //张三第1次借款
        String name = getName(userInfoVo,userId);
        borrowRecord.setName(name);

        save(borrowRecord);
    }

    @Override
    public Pages<BorrowRecordVo> queryBorrowRecord(Integer pageNum, Integer pageSize, BorrowRecordQuery borrowRecordQuery) {

        //分页条件查询
        IPage<BorrowRecord> page = new Page<>(pageNum, pageSize);
//        if (StringUtils.hasText(borrowRecordQuery.getBorrowStatus())){
//            Wrappers.lambdaQuery(BorrowRecord.class)
//                    .or()
//                    .eq(BorrowRecord::getBorrowStatus,borrowRecordQuery.getBorrowStatus());
//
//        };
        LambdaQueryWrapper<BorrowRecord> wrapper = Wrappers.lambdaQuery(BorrowRecord.class)
                .or()
                .eq(StringUtils.hasText(borrowRecordQuery.getBorrowStatus()), //这里不为空  条件查询判断状态
                        BorrowRecord::getBorrowStatus, borrowRecordQuery.getBorrowStatus())
                .or()
                .like(StringUtils.hasText(borrowRecordQuery.getName()),//这里不为空  条件查询name
                        BorrowRecord::getName, borrowRecordQuery.getName())
                .or()     //大于   //这里不为空  范围查询天数
                .gt(!Objects.isNull(borrowRecordQuery.getStartPeriod()), BorrowRecord::getPeriod, borrowRecordQuery.getStartPeriod())
                .or()
                .lt(!Objects.isNull(borrowRecordQuery.getEndPeriod()), BorrowRecord::getPeriod, borrowRecordQuery.getEndPeriod());

        //分页查询的结果
        IPage<BorrowRecord> iPage = page(page, wrapper);
        //记录和总数
        List<BorrowRecord> records = iPage.getRecords();

//        for (BorrowRecord record : records) {
//            BorrowRecordVo borrowRecordVo = new BorrowRecordVo();
//            list.add(borrowRecordVo);
//        }
        //可以 把  集合通过Stream直接 另外一个对象的集合
        List<BorrowRecordVo> list = BeanUtil.copyToList(records, BorrowRecordVo.class);

        long total = iPage.getTotal();

        //封装返回的分页的数据
        Pages<BorrowRecordVo> borrowRecordVoPages = new Pages<>();
        borrowRecordVoPages.setTotal(total);
        borrowRecordVoPages.setList(list);

        return borrowRecordVoPages;
    }

    @Override
    public String changeBorrowRecordStatus(Integer approveStatus, Long borrowRecordId) {

        String status = String.valueOf(approveStatus);

        //01 拿到 borrowRecordId
        // 查询 borrowRecord 借款记录
        BorrowRecord borrowRecord = getById(borrowRecordId);

        //02 生成一个vo对象  BorrowRecordVo
        //把这个对象 发送到  托管平台 (把这个数据传给银行系统)
        BorrowSyncRecordVo borrowSyncRecordVo = new BorrowSyncRecordVo();
        //把 borrowRecord 相同的属性 copy 到  borrowRecordVo
        BeanUtil.copyProperties(borrowRecord, borrowSyncRecordVo);

        //最后 托管平台返回数据进行更新
        //borrowRecord.setStatus(true);
        Result<BaseResult> result = tradeLogApi.syncBorrowRecord(borrowSyncRecordVo);

        //银行返回了数据  更新 borrowRecord状态
        BaseResult baseResult = result.getData();
        if (baseResult.getRespMsg().equals("成功")){
            //更新 借款记录
            update(Wrappers.lambdaUpdate(BorrowRecord.class)
                    .set(BorrowRecord::getBorrowStatus,"SYNC") //借款审核同步 后同步
                    .set(BorrowRecord::getModifyDate,new Date())
                    .set(BorrowRecord::getStatus,status)
                    .eq(BorrowRecord::getId,borrowRecordId)
            );
        }
        return "借款审核成功";
    }

    public String getName(UserInfoVo userInfoVo,Long userId){

        String realName = userInfoVo.getUserName();


        String identityCode = userInfoVo.getIdentityCode();
        String sex = null;
        if (StringUtils.hasText(identityCode) && identityCode.length() == 18){
            //拿到17位字符
            //421123199807145566
            //char c = identityCode.toCharArray()[16];
             sex = identityCode.substring(16, 17);
        }
        String sexN = Integer.parseInt(sex) % 2 == 0 ? "女士":"先生";

        long count = getCount(userId);

        String name = realName + sexN + ",第" + (count + 1) +"次进行借款";

        return name;
    }

    public long getCount(Long userId){
        long count = count(Wrappers.lambdaQuery(BorrowRecord.class).eq(BorrowRecord::getUserId, userId));
        return count;
    }
}
